package com.yantong.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.yantong.constant.ConfigKey;
import com.yantong.mapper.DispatchMapper;
import com.yantong.pojo.*;
import com.yantong.pojo.LifeConfig;
import com.yantong.mapper.PlatformConfigMapper;
import com.yantong.service.ConfigService;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
 * 平台配置服务类
 *
 * @author kanghaixin
 * @date 2018/8/26.14:59
 */

@Service
public class ConfigServiceImpl implements ConfigService {
    @Autowired
    private PlatformConfigMapper platformConfigMapper;
    @Autowired
    private DispatchMapper dispatchMapper;
    private static final String CONFIG_CACHE_NAME = "config";
    private static final String CONFIG_DISPATCH_NAME = "dispatch";
    private static Logger logger = LoggerFactory.getLogger(ConfigServiceImpl.class);



    @Override
    public PlatformConfig getConfigByKey(String configKey) {
        if (StringUtils.isEmpty(configKey)) {
            return null;
        }
        PlatformConfigExample example = new PlatformConfigExample();
        PlatformConfigExample.Criteria criteria = example.createCriteria();
        criteria.andConfigKeyEqualTo(configKey);
        criteria.andCentreIdIsNull();
        List<PlatformConfig> list = platformConfigMapper.selectByExample(example);
        if (CollectionUtils.isEmpty(list)) {
            return null;
        }
        return list.get(0);
    }

    @Override
    public PlatformConfig getConfigByKey(String configKey, Long centreId) {
        if (StringUtils.isEmpty(configKey)) {
            return null;
        }
        PlatformConfigExample example = new PlatformConfigExample();
        PlatformConfigExample.Criteria criteria = example.createCriteria();
        criteria.andConfigKeyEqualTo(configKey);
        if (centreId == null) {
            criteria.andCentreIdIsNull();
        }else {
            criteria.andCentreIdEqualTo(centreId);
        }
        List<PlatformConfig> list = platformConfigMapper.selectByExample(example);
        if (CollectionUtils.isEmpty(list)) {
            if (centreId != null) {
                return this.getConfigByKey(configKey);
            }
            return null;
        }
        return list.get(0);
    }
    
    @Override
    public PlatformConfig getPlatformConfigByKey(String configKey, Long centreId) {
        if (StringUtils.isEmpty(configKey)) {
            return null;
        }
        PlatformConfigExample example = new PlatformConfigExample();
        PlatformConfigExample.Criteria criteria = example.createCriteria();
        criteria.andConfigKeyEqualTo(configKey);
        if (centreId == null) {
            criteria.andCentreIdIsNull();
        }else {
            criteria.andCentreIdEqualTo(centreId);
        }
        List<PlatformConfig> list = platformConfigMapper.selectByExample(example);
        if (CollectionUtils.isEmpty(list)) {
        	PlatformConfig platformConfig = this.getConfigByKey(configKey);
        	if(platformConfig != null) {
	        	if(platformConfig.getConfigId() != null) {
	        	  platformConfig.setConfigId(null);
	        	}
	        	if(platformConfig.getCentreId() != null) {
	            	platformConfig.setCentreId(null);
	        	}
	        	if(platformConfig.getOperatorId() != null) {
	        	  platformConfig.setOperatorId(null);
	        	}
	            return platformConfig;
        	}else {
        		 return null;
        	}
        }
        return list.get(0);
    }

    @Override
    @CacheEvict(value = CONFIG_CACHE_NAME, allEntries = true)
    public int updateConfig(PlatformConfig platformConfig) {
        if (platformConfig == null) {
            return 0;
        }
	    if (ConfigKey.BASE_CONFIG.name().equals(platformConfig.getConfigKey())) {
		    //商家编码为空时生成商家编码mallCode
		    if (StringUtils.isNotEmpty(platformConfig.getConfigValue())) {
			    Map<String, Object> jsonToMap = JSONObject.parseObject(platformConfig.getConfigValue());
			    if(!jsonToMap.containsKey("mallCode")){
				    jsonToMap.put("mallCode", UUID.randomUUID());
				    platformConfig.setConfigValue(JSONObject.toJSONString(jsonToMap));
			    }else if("".equals(jsonToMap.get("mallCode").toString())){
				    jsonToMap.put("mallCode", UUID.randomUUID());
				    platformConfig.setConfigValue(JSONObject.toJSONString(jsonToMap));
			    }
		    }
	    }
        platformConfig.setModifyTime(new Date());
        if (platformConfig.getConfigId() == null) {
            return platformConfigMapper.insertSelective(platformConfig);
        }
        return platformConfigMapper.updateByPrimaryKeySelective(platformConfig);
    }

    @Override
    @Cacheable(value = CONFIG_CACHE_NAME, keyGenerator = "localKeyGenerator")
    public String getImgPrefix() {
        String defaultUrl = "https://o.rjkj7.com";
        PlatformConfig config = this.getConfigByKey(ConfigKey.OSS_CONFIG.name());
        if (config == null) {
            return defaultUrl;
        }
        String configValue = config.getConfigValue();
        if (StringUtils.isEmpty(configValue)) {
            return defaultUrl;
        }

        OssConfig ossConfig = JSON.parseObject(configValue, OssConfig.class);
        if (StringUtils.isEmpty(ossConfig.getDefineUrl())) {
            return defaultUrl;
        }
        return ossConfig.getDefineUrl();
    }

    @Override
    @Cacheable(value = CONFIG_CACHE_NAME, keyGenerator = "localKeyGenerator")
    public TradeConfig getTradeConfig(Long centreId) {
        PlatformConfig config = this.getConfigByKey(ConfigKey.TRADE_CONFIG.name(), centreId);
        if (config == null) {
	        config = this.getConfigByKey(ConfigKey.TRADE_CONFIG.name(), null);
	        if (config == null) {
		        logger.info("not found trade config by configKey:{}, centreId:{}", ConfigKey.TRADE_CONFIG.name(), centreId);
		        return null;
	        }
        }
        String configValue = config.getConfigValue();
        if (StringUtils.isEmpty(configValue)) {
            logger.info("trade config value is null,please check it!");
            return null;
        }
        return JSON.parseObject(configValue, TradeConfig.class);
    }

	@Override
//	@Cacheable(value = CONFIG_CACHE_NAME, keyGenerator = "localKeyGenerator")
	public LifeConfig getLifeConfig(Long centreId) {
		PlatformConfig config = this.getConfigByKey(ConfigKey.LIFE_CONFIG.name(), centreId);
		if (config == null) {
			config = this.getConfigByKey(ConfigKey.LIFE_CONFIG.name(), null);
			if (config == null) {
				logger.info("not found trade config by configKey:{}, centreId:{}", ConfigKey.LIFE_CONFIG.name(), centreId);
				return null;
			}
		}
		String configValue = config.getConfigValue();
		if (StringUtils.isEmpty(configValue)) {
			logger.info("trade config value is null,please check it!");
			return null;
		}
		return JSON.parseObject(configValue, LifeConfig.class);
	}

    @Override
    @Cacheable(value = CONFIG_CACHE_NAME, keyGenerator = "localKeyGenerator")
    public CardConfig getCardConfig(Long centreId) {
        PlatformConfig config = this.getConfigByKey(ConfigKey.CARD_CONFIG.name(), centreId);
        if (config == null) {
            config = this.getConfigByKey(ConfigKey.CARD_CONFIG.name(), null);
            if (config == null) {
                logger.info("not found trade config by configKey:{}, centreId:{}", ConfigKey.CARD_CONFIG.name(), centreId);
                return null;
            }
        }
        String configValue = config.getConfigValue();
        if (StringUtils.isEmpty(configValue)) {
            logger.info("trade config value is null,please check it!");
            return null;
        }
        return JSON.parseObject(configValue, CardConfig.class);
    }

	@Override
    @Cacheable(value = CONFIG_CACHE_NAME, keyGenerator = "localKeyGenerator")
    public OssConfig getOssConfig(String configKey) {
        if (StringUtils.isEmpty(configKey)) {
            logger.info("get oss config key is null!");
        }
        PlatformConfig config = this.getConfigByKey(configKey);
        if (config == null) {
            logger.info("not found oss config by configKey:{}", configKey);
            return null;
        }
        String configValue = config.getConfigValue();
        if (StringUtils.isEmpty(configValue)) {
            logger.info("oss config value is null,please check it!");
            return null;
        }
        return JSON.parseObject(configValue, OssConfig.class);
    }

    @Override
    @Cacheable(value = CONFIG_CACHE_NAME, keyGenerator = "localKeyGenerator")
    public BaseConfig getBaseConfig() {
        PlatformConfig config = this.getConfigByKey(ConfigKey.BASE_CONFIG.name());
        if (config == null) {
            logger.info("not found oss config by configKey:{}", ConfigKey.BASE_CONFIG.name());
            return null;
        }
        String configValue = config.getConfigValue();
        if (StringUtils.isEmpty(configValue)) {
            logger.info("oss config value is null,please check it!");
            return null;
        }
        return JSON.parseObject(configValue, BaseConfig.class);
    }

    @Override
    @Cacheable(value = CONFIG_CACHE_NAME, keyGenerator = "localKeyGenerator")
    public BaseConfig getBaseConfig(Long centreId) {
        PlatformConfig config = this.getConfigByKey(ConfigKey.BASE_CONFIG.name(), centreId);
        if (config == null) {
	        config = this.getConfigByKey(ConfigKey.BASE_CONFIG.name(), null);
	        if (config == null) {
		        logger.info("not found base config by configKey:{}, centreId:{}", ConfigKey.BASE_CONFIG.name(), centreId);
		        return null;
	        }
        }
        String configValue = config.getConfigValue();
        if (StringUtils.isEmpty(configValue)) {
            logger.info("base config value is null,please check it!");
            return null;
        }
        return JSON.parseObject(configValue, BaseConfig.class);
    }

	@Override
	@Cacheable(value = CONFIG_CACHE_NAME, keyGenerator = "localKeyGenerator")
	public CommisConfig getCommissionConfig(Long centreId) {
		PlatformConfig config = this.getConfigByKey(ConfigKey.COMMIS_CONFIG.name(), centreId);
		if (config == null) {
			config = this.getConfigByKey(ConfigKey.COMMIS_CONFIG.name(), null);
			if (config == null) {
				logger.info("not found Commission config by configKey:{}, centreId:{}", ConfigKey.COMMIS_CONFIG.name(), centreId);
				return null;
			}
		}
		String configValue = config.getConfigValue();
		if (StringUtils.isEmpty(configValue)) {
			logger.info("Commission config value is null,please check it!");
			return null;
		}
		return JSON.parseObject(configValue, CommisConfig.class);
	}

	@Override
	public CommisConfig getCommissionConfigByCentreId(Long centreId) {
		PlatformConfig config = this.getConfigByKey(ConfigKey.TRADE_CONFIG.name(), centreId);
		if (config == null) {
			config = this.getConfigByKey(ConfigKey.TRADE_CONFIG.name(), null);
			if (config == null) {
				logger.info("not found Commission config by configKey:{}, centreId:{}", ConfigKey.TRADE_CONFIG.name(), centreId);
				return null;
			}
		}
		String configValue = config.getConfigValue();
		if (StringUtils.isEmpty(configValue)) {
			logger.info("Commission config value is null,please check it!");
			return null;
		}
		return JSON.parseObject(configValue, CommisConfig.class);
	}

	@Override
    @Cacheable(value = CONFIG_CACHE_NAME, keyGenerator = "localKeyGenerator")
    public FooterConfig getFooterConfig(Long centreId) {
        PlatformConfig config = this.getConfigByKey(ConfigKey.FOOTER_CONFIG.name(), centreId);
        FooterConfig pConfig = null;
        if (config == null) {
            pConfig = this.getPlatformFooter();
            return pConfig;
        }
        String configValue = config.getConfigValue();
        if (StringUtils.isEmpty(configValue)) {
            logger.info("footer config value is null,please check it!");
            return null;
        }

        FooterConfig footerConfig = JSON.parseObject(configValue, FooterConfig.class);
        if (StringUtils.isEmpty(footerConfig.getProductInvestmentPic()) || StringUtils.isEmpty(footerConfig.getProductInvestmentTel())) {
            pConfig = this.getPlatformFooter();
            if (pConfig != null) {
                footerConfig.setProductInvestmentPic(pConfig.getProductInvestmentPic());
                footerConfig.setProductInvestmentTel(pConfig.getProductInvestmentTel());
            }
        }

        if (StringUtils.isEmpty(footerConfig.getTeamRecruitPic()) || StringUtils.isEmpty(footerConfig.getTeamRecruitTel())) {
            if (pConfig == null) {
                pConfig = this.getPlatformFooter();
            }
            if (pConfig != null) {
                footerConfig.setTeamRecruitPic(pConfig.getTeamRecruitPic());
                footerConfig.setTeamRecruitTel(pConfig.getTeamRecruitTel());
            }
        }

        if (StringUtils.isEmpty(footerConfig.getSupervisePic()) || StringUtils.isEmpty(footerConfig.getSuperviseTel())) {
            if (pConfig == null) {
                pConfig = this.getPlatformFooter();
            }
            if (pConfig != null) {
                footerConfig.setSupervisePic(pConfig.getSupervisePic());
                footerConfig.setSuperviseTel(pConfig.getSuperviseTel());
            }
        }
        return footerConfig;
    }

    @Cacheable(value = CONFIG_CACHE_NAME, keyGenerator = "localKeyGenerator")
    public FooterConfig getPlatformFooter() {
        PlatformConfig config = this.getConfigByKey(ConfigKey.FOOTER_CONFIG.name());
        if (config == null) {
            return null;
        }
        String configValue = config.getConfigValue();
        if (StringUtils.isEmpty(configValue)) {
            logger.info("footer config value is null,please check it!");
            return null;
        }
        return JSON.parseObject(configValue, FooterConfig.class);
    }

    @Override
    public ShareConfig getShareConfig(Long centreId) {
        PlatformConfig config = this.getConfigByKey(ConfigKey.SHARE_CONFIG.name(), centreId);
        if (config == null) {
            logger.info("not found share config by configKey:{},centreId:{}", ConfigKey.SHARE_CONFIG.name(), centreId);
            config = this.getConfigByKey(ConfigKey.SHARE_CONFIG.name(), null);
            if (config == null) {
                return null;
            }
        }
        String configValue = config.getConfigValue();
        if (StringUtils.isEmpty(configValue)) {
            logger.info("share config value is null,please check it!");
            return null;
        }
        return JSON.parseObject(configValue, ShareConfig.class);
    }

	@Override
	public AssetConfig getAssetConfig(Long centreId) {
		PlatformConfig config = this.getConfigByKey(ConfigKey.ASSET_CONFIG.name(), centreId);
		if (config == null) {
			logger.info("not found asset config by configKey:{},centreId:{}", ConfigKey.ASSET_CONFIG.name(), centreId);
			config = this.getConfigByKey(ConfigKey.ASSET_CONFIG.name(), null);
			if (config == null) {
				return null;
			}
		}
		String configValue = config.getConfigValue();
		if (StringUtils.isEmpty(configValue)) {
			logger.info("asset config value is null,please check it!");
			return null;
		}
		return JSON.parseObject(configValue, AssetConfig.class);
	}


}
